<template>
    <div class="source">
        <!-- 新增来源弹窗 -->
        <el-dialog title="来源文件管理新增" :visible.sync="dialogVisible" width="75%" :close-on-click-modal="false">
            <div>
                <div style="border-bottom: 1px solid #a4a4a4;">
                    <el-form :inline="true" :model="indexSourceCategoryDetailPo">
                        <el-row class="form-row">
                            <el-col :span="10">
                                <el-form-item :label="indexItem.indexType == '1' ? '来源类型：' : '产品类型：'">
                                    <el-select v-model="indexSourceCategoryDetailPo.parentId" placeholder="请选择" size="mini" disabled>
                                        <el-option
                                            :label="item.dictKeyName"
                                            :value="item.dictKey"
                                            v-for="item in indexSourceCodeSelect"
                                            :key="item.dictKey"
                                            >{{ item.dictKey }} {{ item.dictKeyName }}</el-option
                                        >
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="10">
                                <el-form-item :label="indexItem.indexType == '1' ? '来源名称：' : '来源产品：'">
                                    <el-input
                                        v-model="indexSourceCategoryDetailPo.label"
                                        placeholder="请输入来源名称"
                                        size="mini"
                                        style="width:120%"
                                        :disabled="indexItem.level == 4 || addDisabled"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="4">
                                <el-button
                                    type="primary"
                                    size="mini"
                                    style="margin-top: 4px"
                                    @click="addFileSourceCategoryNode"
                                    v-if="indexItem.level == 3"
                                    :disabled="addDisabled"
                                    >添加</el-button
                                >
                            </el-col>
                        </el-row>
                    </el-form>
                </div>
                <div style="margin-top: 25px">
                    <div>
                        <el-button type="primary" @click="handleAddFileBtn('新增')" :disabled="!addFileBtn">新增文件</el-button>
                        <el-button type="danger" @click="handleRemove(multipleitem, '批量删除')" :disabled="!addFileBtn">批量删除</el-button>
                    </div>
                    <el-table
                        :data="indexSourceCategoryDetail"
                        tooltip-effect="dark"
                        style="width: 100%;margin-top:10px"
                        border
                        size="mini"
                        @selection-change="clauseChangeEvent"
                    >
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column type="index" label="序号" width="50"> </el-table-column>
                        <el-table-column prop="versionNumber" label="版本号" width="130" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="fileName" label="文件名称" width="150" show-overflow-tooltip> </el-table-column>
                        <el-table-column
                            :prop="indexItem.indexType == '1' ? 'issueDate' : 'signDate'"
                            :label="indexItem.indexType == '1' ? '发布日期' : '签署日期'"
                            width="130"
                            show-overflow-tooltip
                        >
                            <template slot-scope="scope">
                                <span>{{ dateFormat(indexItem.indexType == '1' ? scope.row.issueDate : scope.row.signDate) || '--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="effectiveDate" label="生效日期" width="120" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span>{{ dateFormat(scope.row.effectiveDate) || '--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="valid" label="是否有效" width="120" show-overflow-tooltip align="center">
                            <template slot-scope="scope">
                                <!-- <span class="el-dropdown-link">{{ scope.row.valid == true ? '是' : '否' }}</span> -->
                                <el-dropdown @command="handleCommand">
                                    <span class="el-dropdown-link"
                                        >{{ scope.row.valid == true ? '是' : '否' }}<i class="el-icon-arrow-down el-icon--right"></i>
                                    </span>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :command="beforeHandleCommand('true', scope.row)">是</el-dropdown-item>
                                        <el-dropdown-item :command="beforeHandleCommand('false', scope.row)">否</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </template>
                        </el-table-column>
                        <el-table-column prop="modifyUser" label="维护人" width="120" show-overflow-tooltip> </el-table-column>
                        <el-table-column prop="modifyDate" label="维护日期" width="120" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span>{{ dateFormat(scope.row.modifyDate) || '--' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="150">
                            <template slot-scope="scope">
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-edit"
                                    topTitle="修改"
                                    v-authCode="B_0188"
                                    @on-click="openAttachementDialog(scope.row, '修改')"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="primary"
                                    icon="el-icon-download"
                                    topTitle="下载"
                                    v-authCode="B_0188"
                                    @on-click="downloadFileBtn(scope.row, '单条下载')"
                                ></RiskIconButton>
                                <RiskIconButton
                                    type="danger"
                                    icon="el-icon-delete"
                                    topTitle="删除"
                                    v-authCode="B_0191"
                                    @on-click="handleRemove(scope.row, '单个删除')"
                                ></RiskIconButton>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleSource('cancel')">取 消</el-button>
                <el-button type="primary" @click="handleSource('confirm')">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 附件上传弹窗 -->
        <el-dialog title="附件上传内容填写" :visible.sync="attachementDialog" width="60%" :close-on-click-modal="false">
            <div>
                <el-form :inline="true" :model="indexDetails" :label-position="right" label-width="110px">
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="版本号">
                                <el-input v-model="indexDetails.versionNumber" size="mini" style="width: 105%" maxlength="20"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="是否有效">
                                <el-select v-model="indexDetails.valid" placeholder="请选择" size="mini">
                                    <el-option label="有效" :value="true"></el-option>
                                    <el-option label="无效" :value="false"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="发布日期" v-if="indexItem.indexType == '1'">
                                <el-date-picker
                                    v-model="indexDetails.issueDate"
                                    placeholder="选择日期"
                                    size="mini"
                                    style="width: 94%"
                                    format="yyyy-MM-dd"
                                    value-format="yyyyMMdd"
                                >
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="签署日期" v-else>
                                <el-date-picker
                                    v-model="indexDetails.signDate"
                                    placeholder="选择日期"
                                    size="mini"
                                    style="width: 94%"
                                    format="yyyy-MM-dd"
                                    value-format="yyyyMMdd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="生效日期">
                                <el-date-picker
                                    v-model="indexDetails.effectiveDate"
                                    placeholder="选择日期"
                                    size="mini"
                                    style="width: 94%"
                                    format="yyyy-MM-dd"
                                    value-format="yyyyMMdd"
                                >
                                </el-date-picker>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="迁移条文">
                                <el-select
                                    v-model="indexDetails.movedIndexSource"
                                    filterable
                                    clearable
                                    placeholder="请选择"
                                    size="mini"
                                    :disabled="moveIndexSourceIs"
                                    @change="changeMovedIndexSource"
                                >
                                    <el-option
                                        :label="item.dictKeyName"
                                        :value="item.dictKey"
                                        v-for="item in indexSourceCodeSelect1"
                                        :key="item.dictKey"
                                        >{{ item.dictKeyName }}</el-option
                                    >
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="迁移版本号">
                                <el-select 
                                    v-model="indexDetails.sourceVersionNumber" 
                                    placeholder="请选择" 
                                    size="mini" 
                                    :disabled="moveIndexSourceIs"
                                >
                                    <el-option 
                                        :label="item.dictKeyName" 
                                        :value="item.dictKey" 
                                        v-for="(item) in sourceVersionNumberList" 
                                        :key="item.dictKey"
                                    >{{item.dictKeyName}}</el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row class="form-row">
                        <el-col :span="12">
                            <el-form-item label="附件">
                                <el-upload
                                    :multiple="true"
                                    :action="actionUrl"
                                    :headers="headerObj"
                                    :with-credentials="true"
                                    list-type="text"
                                    :show-file-list="false"
                                    :on-success="
                                        (res, file, fileList) => {
                                            return uploadFileSuccess(res, file, fileList, '执行标准');
                                        }
                                    "
                                >
                                    <el-button size="small" icon="el-icon-plus" style="border:none">添加文件</el-button>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <UploadFileShow
                        style="margin-left: 60px"
                        :fileList="fileList1"
                        @emitDownLoadFile="downLoadFileBtn"
                        @emitConfirmDelFile="confirmDelFile1"
                    ></UploadFileShow>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="insertSourceDetails">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import UploadFileShow from '../commom/upload-file-show.vue';
import { dateFormat, timeFormat } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { downLoadFile } from '@/utils/request';

@Component({
    name: 'SourceDocumentDialog',
    components: {
        RiskIconButton,
        UploadFileShow,
    },
})
export default class SourceDocumentDialog extends Vue {
    dateFormat = dateFormat;
    @Prop() addSourceDialog;
    @Prop() indexItem;
    @Prop() indexClauseList;
    private dialogVisible: boolean = false;
    private attachementDialog: boolean = false;
    indexSourceCodeSelect = []; // 条目来源分类下拉
    addFileBtn: boolean = false; // 新增文件btn
    indexSourceCategoryDetail = []; // 来源详情信息
    private indexSourceCodeSelect1 = []; // 来源名称select
    typeItem: string = ''; // 新增、编辑
    private actionUrl = ''; // 附件上传url
    fileList1 = []; // 附件
    multipleitem = []; // table多选
    private sourceVersionNumberList = []; // 版本号
    delBtnDisabled: boolean = false;
    headerObj = {
        Authentication: getUser().sessionId,
    };
    indexSourceCategoryDetailPo = {
        indexType: '1', // 指标类型：1:外规类指标、2:产品类指标
        parentId: '', // 来源类型
        label: '', // 指标来源名称
    };
    validTable: string = '是';
    indexDetails = {
        // 来源详情信息
        indexCode: '',
        indexDetailsCode: '',
        versionNumber: '',
        valid: true,
        issueDate: '',
        signDate: '',
        effectiveDate: '',
        movedIndexSource: '',
        sourceVersionNumber: '', // 迁移条文版本号
        fileCode: [],
        files: [],
        fileName: [],
    };
    addDisabled: boolean = false;
    moveIndexSourceIs: boolean = false;
    created() {
        const baseUrl = process.env.ENV_CONFIG === 'project' ? window.project_config.baseUrlApi : process.env.BASE_URL_API;
        this.actionUrl = baseUrl + '/system/upload/1';
    }
    handleSource(parameter) {
        this.$emit('emitSource', false);
    }
    @Watch('addSourceDialog')
    watchAddSourceDialog(val) {
        this.dialogVisible = val;
        if (val == true) {
            if (this.indexItem.indexType == '1') {
                this.getIndexSourceSelect();
            } else if (this.indexItem.indexType == '2') {
                this.getIndexSourceSelectProduct();
            }
            if (this.indexItem.level != 3) {
                this.addFileBtn = true;
                this.indexSourceCategoryDetailPo.parentId = this.indexItem.parentId;
                this.indexSourceCategoryDetailPo.label = this.indexItem.label;
                this.indexDetails.indexCode = this.indexItem.id;
                this.getSourceDetails();
            } else if (this.indexItem.level == 3) {
                this.indexSourceCategoryDetailPo.parentId = this.indexItem.id;
                this.indexSourceCategoryDetail = [];
            }
        } else if (val == false) {
            this.fileList1 = [];
            this.addDisabled = false;
        }
    }
    @Watch('dialogVisible')
    watchDialogVisible(val) {
        if (val == false) {
            this.indexSourceCategoryDetailPo.label = '';
            this.addFileBtn = false;
            this.$emit('emitAddSourceDialog', false);
        }
    }
    @Watch('attachementDialog')
    watchAttachementDialog(val) {
        if (val == true) {
            if (this.indexItem.level != 3) {
                this.indexDetails.indexCode = this.indexItem.id;
            }
            this.getIndexSourceSelect1();
        } else if (val == false) {
            this.fileList1 = [];
            this.sourceVersionNumberList = [];
            this.indexDetails = {
                // 来源详情信息
                indexCode: this.indexItem.id,
                indexDetailsCode: '',
                versionNumber: '',
                valid: true,
                issueDate: '',
                signDate: '',
                effectiveDate: '',
                movedIndexSource: '',
                sourceVersionNumber: '',
                fileCode: [],
                files: [],
                fileName: [],
            };
            this.moveIndexSourceIs = false;
        }
    }
    @Watch('indexClauseList', { immediate: true, deep: true })
    watchIndexClauseList(val) {
        if (this.indexClauseList.length > 0) {
            this.delBtnDisabled = true;
        } else {
            this.delBtnDisabled = false;
        }
    }

    // 获取来源详情信息
    getSourceDetails() {
        this.$axios
            .post('/indexSource/getSourceDetails', {
                indexCode: this.indexDetails.indexCode,
            })
            .then((res: any) => {
                if (res) {
                    this.indexSourceCategoryDetail = [];
                    res.list.forEach(item => this.indexSourceCategoryDetail.push(item));
                }
            });
    }
    // 新增来源详情信息
    insertSourceDetails() {
        if (this.indexDetails.versionNumber == '') {
            this.yh_message_warn('版本号不可为空');
            return;
        }
        if (this.indexDetails.movedIndexSource != '' && this.indexDetails.sourceVersionNumber == '') {
            this.yh_message_warn('迁移版本号不可为空');
            return;
        }
        this.indexDetails.fileCode = [];
        this.indexDetails.fileName = [];
        this.indexDetails.files = [];
        if (this.fileList1) {
            this.fileList1.forEach(item => {
                this.indexDetails.fileCode.push(item.fileNo);
                this.indexDetails.fileName.push(item.name);
                this.indexDetails.files.push({
                    fileNo: item.fileNo,
                    fileName: item.name,
                });
            });
        }
        let dataList = {};
        dataList = {
            // 来源详情信息
            indexCode: this.indexDetails.indexCode,
            indexDetailsCode: this.indexDetails.indexDetailsCode,
            versionNumber: this.indexDetails.versionNumber,
            valid: this.indexDetails.valid,
            issueDate: Number(this.indexDetails.issueDate),
            signDate: Number(this.indexDetails.signDate),
            effectiveDate: Number(this.indexDetails.effectiveDate),
            movedIndexSource: (this.indexDetails.movedIndexSource).split(','),
            sourceVersionNumber: (this.indexDetails.sourceVersionNumber).split(','),
            fileCode: this.indexDetails.fileCode,
            files: this.indexDetails.files,
            fileName: this.indexDetails.fileName,
        };
        if (this.typeItem == '新增') {
            this.$axios.post('/indexSource/insertSourceDetails', dataList).then((res: any) => {
                this.yh_message_success('新增成功!');
                this.attachementDialog = false;
                this.fileList1 = [];
                this.getSourceDetails();
            });
        } else if (this.typeItem == '修改') {
            this.$axios
                .post('/indexSource/updateSourceDetails', dataList)
                .then((res: any) => {
                    this.yh_message_success('修改成功!');
                    this.attachementDialog = false;
                    this.fileList1 = [];
                    this.getSourceDetails();
                    this.moveIndexSourceIs = false;
                })
                .catch(() => {
                    this.moveIndexSourceIs = false;
                    this.attachementDialog = false;
                });
        }
    }
    // 外规类条目来源分类下拉-三级
    getIndexSourceSelect() {
        this.$axios
            .post('/indexSource/indexSourceSelect', {
                dictCode: '',
                dictKey: '',
                dictKeyName: '',
                innerDictionary: '',
                param1: [],
                param2: '',
                param3: '',
                param4: '',
            })
            .then((res: any) => {
                if (res) {
                    this.indexSourceCodeSelect = [];
                    res.forEach(item => this.indexSourceCodeSelect.push(item));
                }
            });
    }
    // 产品类条目来源分类下拉-三级
    getIndexSourceSelectProduct() {
        this.$axios
            .post('/indexSource/indexSourceSelectProduct', {
                dictCode: '',
                dictKey: '',
                dictKeyName: '',
                innerDictionary: '',
                param1: [],
                param2: '',
                param3: '',
                param4: '',
            })
            .then((res: any) => {
                if (res) {
                    this.indexSourceCodeSelect = [];
                    res.forEach(item => this.indexSourceCodeSelect.push(item));
                }
            });
    }
    // 添加文件来源分类节点
    addFileSourceCategoryNode() {
        this.$axios.post('/indexSource/addFileSourceCategoryNode', { ...this.indexSourceCategoryDetailPo }).then((res: any) => {
            if (res) {
                this.indexDetails.indexCode = res;
                this.addFileBtn = true;
                this.yh_message_success('新增成功!');
                this.$emit('emitAddFileSourceCategoryNode');
                this.addDisabled = true;
            }
        });
    }
    // 新增文件Btn
    handleAddFileBtn(param) {
        this.attachementDialog = true;
        this.typeItem = param;
    }
    // 编辑
    openAttachementDialog(param1, param2) {
        this.indexDetails.indexCode = param1.indexCode;
        this.indexDetails.indexDetailsCode = param1.indexDetailsCode;
        this.$axios.get('/indexSource/getIndexSourceDetail/' + param1.indexDetailsCode).then((res: any) => {
            this.indexDetails.files = [];
            if (res) {
                this.attachementDialog = true;
                this.typeItem = param2;
                let resList = res;
                if (res.issueDate) {
                    resList.issueDate = (res.issueDate == 0 ? '' : res.issueDate.toString());
                } else {
                    resList.issueDate = '';
                }
                if (res.signDate) {
                    resList.signDate = (res.signDate == 0 ? '' : res.signDate.toString());
                } else {
                    resList.signDate = '';
                }
                resList.effectiveDate = (res.effectiveDate == 0 ? '' : res.effectiveDate.toString());
                this.indexDetails = resList;
                this.indexDetails.movedIndexSource = (resList.movedIndexSource).join('');
                this.indexDetails.sourceVersionNumber = (resList.sourceVersionNumber).join('');
                if (this.indexDetails.movedIndexSource) {
                    this.getVersionNums(this.indexDetails.movedIndexSource);
                }
                if (this.indexDetails.files) {
                    this.indexDetails.files.forEach(element => {
                        this.fileList1.push({
                            name: element.fileName,
                            fileNo: element.fileNo,
                        });
                    });    
                }
                if (this.indexDetails.movedIndexSource.length != 0 && this.typeItem == '修改') {
                    this.moveIndexSourceIs = true;
                } else {
                    this.moveIndexSourceIs = false;
                }
            }
        });
    }
    // 下载
    downloadFileBtn(param1, param2) {
        // return
        let data = '';
        if (param2 == '单条下载') {
            param1.fileCode.forEach(item => {
                downLoadFile({
                    url: '/system/download/file/' + item,
                    method: 'get',
                });
            });
        } else {
            data = param1.fileNo;
            downLoadFile({
                url: '/system/download/file/' + data,
                method: 'get',
            });
        }
    }
    // 删除btn
    handleRemove(param1, param2) {
        if (param2 == '单个删除') {
            this.$axios.post('/indexSource/deleteSourceDetails/' + param1.indexDetailsCode).then((res: any) => {
                this.yh_message_success('删除成功！');
                this.getSourceDetails();
            });
        } else if (param2 == '批量删除') {
            if (param1.length < 1) {
                this.yh_message_error('选择文件不可为空！');
                return;
            }
            let data = [];
            param1.forEach(item => {
                data.push(item.indexDetailsCode);
            });

            this.$confirm(`确认删除勾选文件?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    this.$axios.post('/indexSource/batchDeleteSourceDetails', data).then((res: any) => {
                        this.yh_message_success('删除成功！');
                        this.getSourceDetails();
                    });
                })
                .catch(() => {
                    this.yh_message_info('已取消删除');
                });
        }
    }
    // 多选
    clauseChangeEvent(checked, row, rowIndex) {
        this.multipleitem = [];
        checked.forEach(item => this.multipleitem.push(item));
    }
    // 条目来源分类下拉-四级
    getIndexSourceSelect1() {
        this.$axios
            .post('/indexSource/indexSourceSelect1', {
                dictCode: this.indexItem.indexType,
                dictKey: '',
                dictKeyName: '',
                innerDictionary: '',
                param1: [],
                param2: '',
                param3: '',
                param4: '',
                childrenDictKey: this.indexItem.id,
            })
            .then((res: any) => {
                if (res) {
                    this.indexSourceCodeSelect1 = [];
                    res.forEach(item => this.indexSourceCodeSelect1.push(item));
                }
            });
    }
    // 获取当前来源的所有版本号
    getVersionNums(indexCode) {
        this.$axios.post('/indexSource/getVersionNums/' + indexCode).then((res: any) => {
            if (res) {
                this.sourceVersionNumberList = [];
                res.forEach(item => this.sourceVersionNumberList.push(item))
            }
        });
    }
    // 迁移条文选择
    changeMovedIndexSource(param) {
        console.log(param)
        if (param) {
            this.getVersionNums(param)
        } else {
            this.sourceVersionNumberList = [];
        }
    }
    // 是否有效
    handleCommand(command) {
        let data = command.command;
        if (command.index == 'false') {
            data.valid = false;
        } else if (command.index == 'true') {
            data.valid = true;
        }
        this.$axios.post('/indexSource/updateSourceDetails', data).then((res: any) => {
            this.yh_message_success('修改成功!');
            this.getSourceDetails();
        });
    }
    beforeHandleCommand(index, command) {
        // index我这里是遍历的角标，即你需要传递的额外参数
        return {
            index: index,
            command: command,
        };
    }
    // 文件上传
    uploadFileSuccess(res, file, fileList, type) {
        this.fileList1.push({
            name: res.data.fileName,
            url: res.data.relativePath,
            fileNo: res.data.fileNo,
        });
    }
    // 下载文件
    downLoadFileBtn(param) {
        downLoadFile({
            url: '/system/download/file/' + param.fileNo,
            method: 'get',
        });
    }
    // 删除已上传文件
    confirmDelFile1(param) {
        this.fileList1.forEach((item, index) => {
            if (item.fileNo == param.fileNo) {
                this.fileList1.splice(index, 1);
            }
        });
    }
}
</script>
<style lang="scss" scoped>
.source {
    height: calc(98vh - 7px);
    background: #ffffff;
}
</style>
